/**
 * 商品信息管理
 */
var Goods = {
    tableId: "goodsTable",
    prev: {
        pName: "",
        parentId: ""
    }
};

layui.use(['table', 'admin', 'ax','form','tableSelect'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var form = layui.form;
    var admin = layui.admin;
    var tableSelect = layui.tableSelect;


    /**
     * 初始化表格的列
     */
    Goods.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: 'id'},
            {field: 'name', sort: true, align:'center',title: '商品中文名'},
            {field: 'goodsNo', sort: true, align:'center',title: '商品编号'},
            {field: 'title', sort: true,align:'center', title: '商品标题'},
            {field: 'batchNo', sort: true, align:'center',title: '批次号'},
            {field: 'shipFee', sort: true, align:'center',title: '运费'},
            {field: 'description', sort: true,align:'center', title: '商品详情'},
            {field: 'headpic', sort: true,hide: true, align:'center',title: '商品主图'},
            {field: 'status', sort: true, title: '商品状态', templet: '#statusTpl', align:'center',},
            {field: 'updateTime', sort: true, title: '最后修改时间'},
            {align: 'center', toolbar: '#tableBar', title: '操作',minWidth: 180}
        ]];
    };

    /**
     * 弹出添加对话框
     */
    Goods.openAddDlg = function () {
        admin.putTempData('formOk', false);
        layui.admin.open({
            type: 2,
            title: '添加商品信息',
            anim: 1,
            area:["100%","100%"],
            maxmin:true,
            content: Feng.ctxPath + '/goods/add',
            end: function () {
                admin.getTempData('formOk') && table.reload(Goods.tableId);
            }
        });
    };

    /**
     * 导出excel按钮
     */
    Goods.exportExcel = function () {

        var checkRows = table.checkStatus(Goods.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要导出的数据");
        } else {
            var a=[["0","下架"],["1","上架"]]
            for(var i=0;i<checkRows.data.length;i++){
                //根据枚举匹配相应的状态
                var value = Feng.MatchStatus(a, checkRows.data[i].status,"无");
                checkRows.data[i].status=value
            }
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }
    };

    /**
     * 点击编辑
     *
     * @param data 点击按钮时候的行数据
     */
    Goods.openEditDlg = function (data) {
        admin.putTempData('formOk', false);
        layui.admin.open({
            type: 2,
            title: '修改商品信息',
            anim: 1,
            area:["100%","100%"],
            maxmin:'true',
            content: Feng.ctxPath + '/goods/edit?id=' + data.id,
            end: function () {
                admin.getTempData('formOk') && table.reload(Goods.tableId);
            }
        });
    };

    /**
     * 点击查看详情
     * @param data
     */

    Goods.openDetailDlg = function (data) {
        admin.putTempData('formOk', false);
        layui.admin.open({
            type: 2,
            title: '商品信息',
            anim: 1,
            area:["70%","70%"],
            maxmin:'true',
            content: Feng.ctxPath + '/goods/goodsDetail?id=' + data.id,
            end: function () {
                admin.getTempData('formOk') && table.reload(Goods.tableId);
            }
        });
    };

    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    Goods.onDeleteItem = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/goods/delete", function (data) {
                Feng.success("删除成功!");
                table.reload(Goods.tableId);
            }, function (data) {
                Feng.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Feng.confirm("是否删除?", operation);
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + Goods.tableId,
        url: Feng.ctxPath + '/goods/list',
        page: true,
        height: "full-50",
        cellMinWidth: 100,
        cols: Goods.initColumn()
    });


    /**
     * 点击查询按钮
     */
    Goods.search = function () {
        var queryData = {};
        queryData['name'] = $("#name").val();
        queryData['batchNo'] = $("#batchNo").val();
        queryData['status'] = $("#status").val();
        queryData['goodsNo'] = $("#goodsNo").val();
        queryData['parentId'] = $("#parentId").val();
        queryData['labelId'] = $("#labelId").val();
        tableResult.reload({where: queryData
            ,page: {
                curr: 1 //重新从第 1 页开始
            }
        });
    };



    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        Goods.search();
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        Goods.openAddDlg();
    });

    // 导出excel
    $('#btnExp').click(function () {
        Goods.exportExcel();
    });

    // 工具条点击事件
    table.on('tool(' + Goods.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'edit') {
            Goods.openEditDlg(data);
        } else if (layEvent === 'delete') {
            Goods.onDeleteItem(data);
        }else if (layEvent === 'detail') {
            Goods.openDetailDlg(data);
        }
    });

    // 修改user状态
    form.on('switch(status)', function (obj) {
        var id = obj.elem.value;
        var checked = obj.elem.checked ? true : false;
        Goods.changeGoodsStatus(id, checked);
    });

    Goods.changeGoodsStatus = function (id, checked) {
        if (checked) {
            var ajax = new $ax(Feng.ctxPath + "/goods/shelve", function (data) {
                Feng.success("上架成功!");
            }, function (data) {
                Feng.error("上架失败!");
                table.reload(Goods.tableId);
            });
            ajax.set("status", "1");
            ajax.set("id", id);
            ajax.start();
        } else {
            var ajax = new $ax(Feng.ctxPath + "/goods/shelve", function (data) {
                Feng.success("下架成功!");
            }, function (data) {
                Feng.error("下架失败!" + data.responseJSON.message + "!");
                table.reload(Goods.tableId);
            });
            ajax.set("id", id);
            ajax.set("status", "0");
            ajax.start();
        }
    };

    // 表格tr双击弹窗事件，修改或者查看详情
    $(document).on('dblclick', '.layui-table>tbody>tr', function (){
        var recordId = $(this).children('td:eq(1)').text();
        var data = {id: recordId};
        Goods.openDetailDlg(data);
    })

    // 点击父级菜单
    $('#pName').click(function () {
        var formName = encodeURIComponent("parent.Goods.prev.pName");
        var formId = encodeURIComponent("parent.Goods.prev.parentId");
        var treeUrl = encodeURIComponent("/category/selectCategoryTreeList");
        layer.open({
            type: 2,
            title: '父级菜单',
            area: ['300px', '400px'],
            content: Feng.ctxPath + '/system/commonTree?formName=' + formName + "&formId=" + formId + "&treeUrl=" + treeUrl,
            end: function () {
                $("#parentId").val(Goods.prev.parentId);
                $("#pName").val(Goods.prev.pName);
            }
        });
    });

    //表格选择
    tableSelect.render({
        elem: '#labelName',	//定义输入框input对象 必填
        checkedKey: 'id', //表格的唯一建值，非常重要，影响到选中状态 必填
        searchKey: 'labelName',	//搜索输入框的name值 默认keyword-
        searchPlaceholder: '标签名',	//搜索输入框的提示文字 默认关键词搜索
        table: {	//定义表格参数，与LAYUI的TABLE模块一致，只是无需再定义表格elem
            url:Feng.ctxPath+'/label/list?recordStatus=1',
            cols: [[
                {type: 'checkbox'},
                {field: 'id', hide: true, title: 'id'},
                {field: 'labelName', sort: true, align:'center',title: '商品标签'},
            ]]
        },
        done: function (elem, data) {
            //选择完后的回调，包含2个返回值 elem:返回之前input对象；data:表格返回的选中的数据 []
            //拿到data[]后 就按照业务需求做想做的事情啦~比如加个隐藏域放ID...
            console.log(data.data.length)
            console.log(data.data[0].id)
            //alert(data[0][0].id)
            // elem.val(data.data);
            var a="";
            var b="";
            for (var i=0;i<data.data.length;i++){
                a+=data.data[i].id+",";
                b+=data.data[i].labelName+",";
            }
            elem.parent().find("#labelId").val(a)
            elem.parent().find("#labelName").val(b)


        }
    })
//默认值只需要在触发input上添加 ts-selected="1,2,3" 属性即可 值需与checkedKey对应


});
